package com.teach.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.teach.Const;

@WebServlet("/code.let")
public class CodeServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Random r = new Random();
		String code = ""+r.nextInt(10)+r.nextInt(10)+r.nextInt(10)+r.nextInt(10);//随机要绘制的文字
//		System.out.println(code);
		request.getSession().setAttribute(Const.CODE_NAME, code);
		
		int width = 139;
		int height = 48;
		
			
		BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = img.getGraphics();
		
		//填充白色背景
		g.setColor(new Color(255, 255, 255));
		g.fillRect(0, 0, width, height);
		
		
		//画干扰线(多条)
		for(int i=0;i<height/2;i++){
			g.setColor(new Color(150+r.nextInt(100),150+r.nextInt(100),150+r.nextInt(100)));//随机颜色 150-250
			g.drawLine(0, r.nextInt(height), width, r.nextInt(height));
		}
		
		//绘制文字
		int fontSize=36;
		g.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
		int w = width/code.length();
		for(int i=0;i<code.length();i++){
			g.setColor(new Color(50+r.nextInt(150),50+r.nextInt(150),50+r.nextInt(150)));//随机颜色 50-200
			g.drawString(code.substring(i,i+1), i*w, height-r.nextInt(height-fontSize));
		}
		
		response.reset();
		response.setContentType("image/jpeg");
		ImageIO.write(img, "jpg", response.getOutputStream());
		response.flushBuffer();
	}
}
